import 'dart:async';
import 'dart:convert';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'dart:ui' as ui;

import '../event/user_id_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../serial/three_to_one_manager.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import 'clipper.dart';


class AuthDialog{

  RxString authType = RxString('1');
  RxBool initialize = RxBool(false);

  late List<CameraDescription> _cameras;
  CameraController? controller;

  Timer? _timer;

  var countTime = 60;

  CameraImage? currentImage;

  ThreeToOneManager manager = ThreeToOneManager();

  final GlobalKey _globalKey = GlobalKey();



  _openCamera() async {
    _cameras = await availableCameras();
    controller = CameraController(_cameras[0], ResolutionPreset.max);
    controller!.initialize().then((_) {
      initialize.value = true;
      // _startImageStream();
      _start();
    }).catchError((Object e) {
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            toastError('Camera CameraAccessDenied');
            break;
          default:
            toastError('camera error');
            _disposeCamera();
            break;
        }
      }
    });
  }

  _disposeCamera(){
    initialize.value = false;
    controller?.dispose();
    controller = null;
    _timer?.cancel();
    _timer = null;
  }

  _start(){
    countTime = settingEntity.actionTime??60;
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      if (countTime <= 0) {
        if(_timer!=null){
          _timer!.cancel();
          _timer = null;
          toastWarn('人脸认证超时');
        }
        return;
      }
      countTime = countTime-5;
      _widgetToImage();
    });
  }

  // _computeTakePicture() {
  //   if (controller != null) {
  //     controller!.takePicture().then((file){
  //       file.readAsBytes().then((bytes){
  //         String base64 = base64Encode(bytes);
  //         String base64Image = "data:image/png;base64,$base64";
  //         faceSearch(base64Image).then((data){
  //           if(data.$1 != null){
  //             if(controller != null && currentTask.uid == null){
  //               eventFactory.fire(UserIdEvent(data.$1.userId));
  //               timer.cancel();
  //               _disposeCamera();
  //             }
  //           }else{
  //             toastWarn('${data.$2}');
  //           }
  //         });
  //         File f = File.fromUri(Uri.file(file.path));
  //         f.delete();
  //       });
  //     });
  //   }
  // }

  _widgetToImage() {
    RenderRepaintBoundary render = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    render.toImage().then((image){
      image.toByteData(format: ui.ImageByteFormat.png).then((byteData){
        if(byteData != null){
          String base64 = base64Encode(byteData.buffer.asUint8List());
          String base64Image = "data:image/png;base64,$base64";
          faceSearch(base64Image).then((data){
            if(data.$1 != null){
              if(controller != null && currentTask.uid == null){
                eventFactory.fire(UserIdEvent(data.$1.userId));
                timer.cancel();
                _disposeCamera();
              }
            }else{
              toastWarn('${data.$2}');
            }
          });
        }
      });
    });
  }

  authTypeDialog() async {
    timer.startCountDown(CountDownMode.action,(){
      _disposeCamera();
      manager.setMode(Mode.none);
      Get.until((route) => route.isFirst);
    });

    Get.defaultDialog(
      title: "",
      barrierDismissible: false,
      contentPadding:EdgeInsets.zero,
      titlePadding:EdgeInsets.zero,
      backgroundColor: Colors.transparent,
      content: Container(
        width: 320.w,
        height: 412.h,
        decoration: const BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(
                "assets/images/dialog_bg.png",
              ),
            )
        ),
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            Positioned(
                top: 5.h,
                child: Container(
                  height: 30.h,
                  alignment: Alignment.center,
                  child: Text('身份认证',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 18.sp,)),
                )
            ),
            Positioned(
                top: 5.h,
                right: 28.w,
                child: Container(
                  height: 30.h,
                  alignment: Alignment.center,
                  child: Obx(() => Text('${timer.actionTime.value}s',style: TextStyle(color: Colors.white,fontSize: 10.sp),textAlign: TextAlign.center,)),
                )
            ),

            Positioned(
                top: 5.h,
                right: 10.w,
                child: InkWell(
                  onTap: (){
                    manager.setMode(Mode.none);
                    timer.cancel();
                    _disposeCamera();
                    Get.back();
                  },
                  child: Container(
                      height: 30.h,
                      alignment: Alignment.center,
                      child: Icon(Icons.close,color: Colors.white,size: 20.sp,)
                  ),
                )
            ),
            Positioned(
                top: 110.h,
                height: 165.h,
                left: 90.w,
                right: 90.w,
                child: Obx(() => authType.value == '1'?Image.asset("assets/images/reader_big.png",width: 100.w,fit: BoxFit.fitWidth,)
                    : authType.value == '2'?Image.asset("assets/images/id_big.png",width: 100.w,fit: BoxFit.fitWidth)
                    :initialize.value?Align(
                        child:
                          RepaintBoundary(
                            key: _globalKey,
                            child: ClipOval(
                              clipper: ClipperOvalPath(160.w,80.h),
                              child:  Transform.scale(
                                scale: 2,
                                child: Transform.translate(offset: Offset(0,10.h),
                                  child: RotatedBox(
                                    quarterTurns: settingEntity.rotate??2,
                                    child: AspectRatio(
                                        aspectRatio: 0.56,
                                        child: CameraPreview(controller!)
                                    ),
                                  ),),
                              ),
                            ),
                          ),
                      )
                    :const SizedBox()
                )
            ),
            Positioned(
                top: 290.h,
                height: 110.h,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if(settingEntity.auth!.contains('1'))...[
                      InkWell(
                          onTap: (){
                            if(authType.value != '1'){
                              _onTap('1');
                            }
                          },
                          child: Container(
                            margin: EdgeInsets.only(top: 3.h,bottom: 3.h),
                            child: Obx(() => Image.asset("assets/images/${authType.value == '1'?'reader_select':'reader_un_select'}.png",width: 180.w,fit: BoxFit.fitWidth,),),
                          )
                      )
                    ],
                    if(settingEntity.auth!.contains('2'))...[
                      InkWell(
                          onTap: (){
                            if(authType.value != '2'){
                              _onTap('2');
                            }
                          },
                          child: Container(
                            margin: EdgeInsets.only(top: 3.h,bottom: 3.h),
                            child: Obx(() => Image.asset("assets/images/${authType.value == '2'?'id_select':'id_unselect'}.png",width: 180.w,fit: BoxFit.fitWidth,),),
                          )
                      )
                    ],
                    if(settingEntity.auth!.contains('3'))...[
                      InkWell(
                          onTap: (){
                            if(authType.value != '3'){
                              _onTap('3');
                            }
                          },
                          child: Container(
                              margin: EdgeInsets.only(top: 3.h,bottom: 3.h),
                              child: Obx(() => Image.asset("assets/images/${authType.value == '3'?'face_select':'face_un_select'}.png",width: 180.w,fit: BoxFit.fitWidth,),)
                          )
                      )
                    ],
                  ],
                )
            ),
          ],
        ),
      ),
    );
    if(settingEntity.auth != null && settingEntity.auth!.isNotEmpty){
      authType.value = settingEntity.auth!.substring(0,1);
      _onTap(authType.value);
    }
  }

  _onTap(tap){
    if(tap == '1'){
      currentTask.authType = 1;
      authType.value = '1';
      tts.speak('请刷读者卡');
      if(settingEntity.analysisReader == 'xy'){
        _setModeAndStart(Mode.reader);
      }
      if(settingEntity.analysisReader == 'py'){
        _setModeAndStart(Mode.readerBlock);
      }
      _disposeCamera();
    }else if(tap == '2'){
      currentTask.authType = 2;
      authType.value = '2';
      tts.speak('请刷身份证');
      _setModeAndStart(Mode.identify);
      _disposeCamera();
    }else{
      currentTask.authType = 3;
      authType.value = '3';
      tts.speak('请刷人脸');
      _setModeAndStart(Mode.none);
      _openCamera();
    }
  }

  _setModeAndStart(Mode mode){
    try{
      manager.setModeAndStart(Mode.none);
      Future.delayed(const Duration(milliseconds: 100),(){
        manager.setModeAndStart(mode);
      });
    }catch(e){
      toastWarn('三合一读写器配置错误');
      print(e);
    }
  }

}